package com.tul.vapp.servicecenter.filter;

import com.tul.vapp.servicecenter.common.UriConstant;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Pattern;

/**
 * login filter
 *
 * @author wujunlei
 * @version 1.0
 * @since 2018/1/2
 */
public class LoginFilter implements Filter {

    /**
     * 忽略验证的文件后缀
     */
    private String ignores;

    /**
     * 匹配器
     */
    private Pattern pattern;

    /**
     * init
     *
     * @param filterConfig filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ignores = filterConfig.getInitParameter("ignores");
        if (StringUtils.isEmpty(ignores)) {
            return;
        }
        String[] ignorePatterns = ignores.split(",");
        String reg = ".*(";

        for (int i = 0; i < ignorePatterns.length; i++) {
            reg += "\\" + ignorePatterns[i].replace("\n", "").replace("\r\n", "").trim();
            if (i < ignorePatterns.length - 1) {
                reg += "|";
            } else {
                reg += ")";
            }
        }
        reg += "$";
        pattern = Pattern.compile(reg);
    }

    /**
     * do filter
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        //todo:wjl complete this code
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        if (pattern.matcher(uri).matches()) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (CollectionUtils.arrayToList(UriConstant.WHITE_LIST).contains(uri)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("user");
        if (user != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            ((HttpServletResponse) servletResponse).sendError(401);
        }
    }

    /**
     * destory
     */
    @Override
    public void destroy() {

    }
}
